package com.wyhello.tube4.spring.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.wyhello.tube4.pojo.Appendix;
import com.wyhello.tube4.pojo.Dictionary;
import com.wyhello.tube4.pojo.Exchange;
import com.wyhello.tube4.pojo.Position;
import com.wyhello.tube4.pojo.Reside;
import com.wyhello.tube4.pojo.Tube;
import com.wyhello.tube4.pojo.User;
import com.wyhello.tube4.spring.model.AppendixModel;
import com.wyhello.tube4.spring.model.ExchangeRecordsModel;
import com.wyhello.tube4.spring.model.MeterRecordsModel;
import com.wyhello.tube4.spring.model.ResideRecordsModel;
import com.wyhello.tube4.util.DateUtil;
@Controller
public class ExchangeRecordsController {
	@Autowired
	private ExchangeRecordsModel exchangeRecordsModel;
	@Autowired
	private MeterRecordsModel meterRecordsModel;
	@Autowired
	private ResideRecordsModel resideRecordsModel;
	@Autowired
	private AppendixModel appendixModel;
	
	/**
	 * 保存换管记录并更新位置信息
	 * @param change
	 * @param position
	 * @return
	 */
	@RequestMapping("/exchange/save")
	public String save(Position position,String strtime,String worker,int boilerID, int surfaceID, int rowID, int tubeID,
			int positionID,String reason,@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request){
		Exchange change = new Exchange();
		Position p = resideRecordsModel.getPositionById(positionID);
		//清除废弃位置记录
		p.getRealitys().clear();
		p.getMacroscopics().clear();
		//保存新添位置信息
		p.setStuff(position.getStuff());
		p.setOuterDiameter(position.getOuterDiameter());
		p.setWallThick(position.getWallThick());
		p.setSolder(position.getSolder());
		p.setHeat(position.isHeat());
		p.setUsing(position.isUsing());
		p.setOutLimitValue(position.getCreepLimitValue());
		p.setOutWarnValue(position.getCreepWarnValue());
		p.setCreepLimitValue(position.getCreepLimitValue());
		p.setCreepWarnValue(position.getCreepWarnValue());
		p.setWallLimitValue(position.getWallLimitValue());
		p.setWallWarnValue(position.getWallWarnValue());
		p.setSpeedValue(position.getSpeedValue());
		p.setLifeValue(position.getLifeValue());
		p.setWeldMethod(position.getWeldMethod());
		resideRecordsModel.updatePosition(p);
		//保存换管记录
		change.setReason(reason);
		change.setWorkSpace(worker);
		change.setTime(DateUtil.str2Date(strtime, null));
		change.setPosition(p);
		change.setBoilerId(boilerID);
		change.setSurfaceId(surfaceID);
		change.setRowId(rowID);
		change.setTubeId(tubeID);
		
		exchangeRecordsModel.saveChange(change);
		
		String path = request.getSession().getServletContext().getRealPath("appendix");
		String oFileName = file.getOriginalFilename(); 
        int beginIndex = oFileName.lastIndexOf(".");
        String extention = "";
        if(beginIndex != -1){
        	extention = oFileName.substring(beginIndex);
        }
        
        String fileName = DateUtil.date2Str(new Date(), "yyyyMMddHHmmss") + "_" + String.format("%04d",(int)(Math.random()*10000))+ extention; 
        
		File files = new File(path, fileName);  
        if(!files.exists()){  
            files.mkdirs();  
        }
        try {  
            file.transferTo(files);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }
        
        Appendix appendix=new Appendix();
        appendix.setName(fileName);
        appendix.setOrgname(oFileName);
        appendix.setUploaddate(new Date());
        appendix.setSuffix(extention.toLowerCase());
        appendix.setPath("appendix");
        appendix.setObjid(change.getId());
        User user=(User)request.getSession().getAttribute("user");
        appendix.setUserid(user.getId());
        appendix.setObjname("exchange");
        appendixModel.saveAppendix(appendix);
        
		return "success";
	}
	
	/**
	 * 批量删除换管记录
	 * @param request
	 * @return
	 */
	@RequestMapping("/exchange/delete")
	public String delete(HttpServletRequest request){
		String ids = request.getParameter("deletid");
		exchangeRecordsModel.deleteChange("("+ids+")"); 
		return "success";
	}
	
	/**
	 * 查询全部换管记录
	 * @return
	 */
	@RequestMapping("/exchange/queryall")
	public ModelAndView queryall(){
		List<Exchange> changes = exchangeRecordsModel.queryChange();
		ModelAndView model = new ModelAndView("listall", "changes", changes);
		
		return model;
	}
	
	/**
	 * 查询锅炉
	 * 
	 * 查询锅炉并在页面上显示锅炉和关联的受热面信息
	 * @return
	 */
	@RequestMapping("/exchange/query")
	public ModelAndView query(){
		List<Reside> boilers =  meterRecordsModel.queryResideByBoiler();
		ModelAndView model = new ModelAndView("list","boilers",boilers);
		return model;
	}
	
	/**
	 * 根据受热面id查询有换管记录的管排信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/exchange/queryExchangeRows")
	public ModelAndView queryExchangeRows(int id,String url){
		List<Reside> rows = exchangeRecordsModel.queryExchangeRowBySurfaceId(id);
		ModelAndView model = new ModelAndView(url,"rows",rows);
		return model;
	}
	
	
	/**
	 * 根据管排id查询所有有换管记录的管信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/exchange/getTubes")
	public ModelAndView getTubes(int id,String url){
		List<Tube> tubes = exchangeRecordsModel.queryExchangeTubeByRowId(id);
		ModelAndView model = new ModelAndView(url,"tubes",tubes);
		return model;
	}
	
	/**
	 * 根据管id查询所有有换管记录的位置信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/exchange/getPositions")
	public ModelAndView getPositions(int id,String url){
		List<Position> positions = exchangeRecordsModel.queryExchangePositionByTubeId(id);
		ModelAndView model = new ModelAndView(url,"positions",positions);
		return model;
	}
	
	/**
	 * 根据位置id查询所有有换管记录信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/exchange/getExchanges")
	public ModelAndView getExchanges(int id,String url){
		List<Exchange> exchanges = exchangeRecordsModel.queryExchangeByPositionId(id);
		List<Exchange> temp=new ArrayList<Exchange>();
		for(int i=0;i<exchanges.size();i++)
		{
			Exchange exchange=(Exchange)exchanges.get(i);
			List<Appendix> appendixs = appendixModel.getAppendixList(exchange.getId(),"exchange");
			exchange.setAppendixs(appendixs);
			temp.add(exchange);
		}
		ModelAndView model = new ModelAndView(url,"exchanges",temp);
		
		return model;
	}
	
	
	/**
	 * 根据id删除换管记录
	 * @param request
	 * @return
	 */
	@RequestMapping("/exchange/delById")
	public void delById(int id,HttpServletResponse response){
		int count = exchangeRecordsModel.deleteExchangeById(id); 
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(count);
	}
	
	/**
	 * 查询锅炉信息
	 * @return
	 */
	@RequestMapping("/exchange/queryRealitys")
	public ModelAndView queryRealitys(){
		List<Reside> boilers =  meterRecordsModel.queryResideByBoiler();
		List<Dictionary> dictionary = resideRecordsModel.queryDictionaryByType();
		List<Dictionary> dictionaryWeld = resideRecordsModel.queryDictionaryByWeld();
		List<Dictionary> dictionaryWire = resideRecordsModel.queryDictionaryByWire();
		ModelAndView model = new ModelAndView("addExchange");
		model.addObject("boilers",boilers);
		model.addObject("dictionarys", dictionary);
		model.addObject("dictionaryWeld", dictionaryWeld);
		model.addObject("dictionaryWire", dictionaryWire);
		return model;
	}
	/**
	 * 查询指定锅炉下的受热面
	 * @param parentid
	 * @return
	 */
	@RequestMapping("/exchange/querySurface")
	public void querySurface(int parentid,HttpServletResponse response){
		Reside reside = resideRecordsModel.getResideById(parentid);
		Set<Reside> surfaceSet = reside.getResides();
		Map<Integer,String> map = new HashMap<Integer,String>();
		for (Reside surface : surfaceSet) {
			map.put(surface.getId(), surface.getName());
		}
		JSONObject json = JSONObject.fromObject(map);
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(json);
	}
	/**
	 * 查询指定受热面下的管排
	 * @param parentid
	 * @return
	 */
	@RequestMapping("/exchange/queryRows")
	public void queryRows(int parentid,HttpServletResponse response){
		Reside reside = resideRecordsModel.getResideById(parentid);
		Set<Reside> rows = reside.getResides();
		Map<Integer,String> map = new HashMap<Integer,String>();
		for (Reside row : rows) {
			map.put(row.getId(), row.getName());
		}
		JSONObject json = JSONObject.fromObject(map);
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(json);
	}
	/**
	 * 查询指定管排下的管
	 * @param parentid
	 * @return
	 */
	@RequestMapping("/exchange/queryTube")
	public void queryRow(int parentid,HttpServletResponse response){
		Reside reside = resideRecordsModel.getResideById(parentid);
		Set<Tube> tubes = reside.getTubes();
		Map<Integer,String> map = new HashMap<Integer,String>();
		for (Tube tube : tubes) {
			map.put(tube.getId(), tube.getName());
		}
		JSONObject json = JSONObject.fromObject(map);
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(json);
	}
	/**
	 * 查询指定管的位置
	 * @param parentid
	 * @return
	 */
	@RequestMapping("/exchange/queryPosition")
	public void queryPosition(int parentid,HttpServletResponse response){
		Tube tube = resideRecordsModel.getTubeById(parentid);
		Set<Position> position = tube.getPositions();
		Map<Integer,String> map = new HashMap<Integer,String>();
		for (Position positions : position) {
			map.put(positions.getId(), positions.getPositionName());
		}
		JSONObject json = JSONObject.fromObject(map);
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(json);
	}
}
